package com.mytoutou.playermanager.player_manager.utils;


import com.mytoutou.playermanager.player_manager.Config;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class HandlerThreadExtension extends HandlerThread {

    private static final boolean SHOW_LOGS = Config.SHOW_LOGS;

    private static final String TAG = HandlerThreadExtension.class.getSimpleName();

    private EventHandler mHandler;
    private final Object mStart = new Object();

    /**
     * @param name
     * @param setupExceptionHandler
     */
    public HandlerThreadExtension(String name, boolean setupExceptionHandler) {
        super(name);
        if (setupExceptionHandler) {
            setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread thread, Throwable ex) {

                    if (SHOW_LOGS) Logger.v(TAG, "uncaughtException, " + ex.getMessage());
                    ex.printStackTrace();
                    System.exit(0);
                }
            });
        }
    }

    @Override
    protected void onLooperPrepared() {
        if (SHOW_LOGS) Logger.v(TAG, "onLooperPrepared " + this);

        mHandler = new EventHandler(EventRunner.create(false));
        mHandler.postTask(new Runnable() {
            @Override
            public void run() {
                synchronized (mStart) {
                    mStart.notifyAll();
                }
            }
        });
    }

    public void post(Runnable r) {

        mHandler.postTask(r);
        boolean successfullyAddedToQueue = mHandler.hasInnerEvent(r);
        if (SHOW_LOGS) Logger.v(TAG, "post, successfullyAddedToQueue " + successfullyAddedToQueue);

    }

    public void postAtFrontOfQueue(Runnable r) {
        mHandler.postTask(r);
    }

    public void startThread() {
        if (SHOW_LOGS) Logger.v(TAG, ">> startThread");

        synchronized (mStart) {
            start();
            try {
                mStart.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (SHOW_LOGS) Logger.v(TAG, "<< startThread");

    }

    public void postQuit() {
        mHandler.postTask(new Runnable() {
            @Override
            public void run() {
                if (SHOW_LOGS) Logger.v(TAG, "postQuit, run");
                EventRunner.current().stop();
            }
        });
    }

    public void remove(Runnable runnable) {
        mHandler.removeTask(runnable);
    }


}

